package com.qys.livesMall.kafka.service.impl;

import com.qys.livesMall.kafka.entity.log.SystemLog;
import com.qys.livesMall.kafka.service.SystemLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dp
 * Date: 2023/06/06
 * Time: 10:35
 * DESCRIPTION:
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SystemLogServiceImpl implements SystemLogService {

    private final MongoTemplate mongoTemplate;

    /**
     * 保存后台操作日志
     *
     * @param systemLog {@link  SystemLog}
     */
    @Override
    public void save(SystemLog systemLog) {
        mongoTemplate.save(systemLog);
    }

    /**
     * 分页查询系统操作日志信息
     *
     * @param page
     * @param startTime 开始时间
     * @param endTime   结束时间
     */
    @Override
    public Page<SystemLog> page(PageRequest page, LocalDateTime startTime, LocalDateTime endTime) {
        // 总数
        long totalCount;

        // 构造查询条件
        Query query = new Query();

        //判断是否需要按时间查询
        if (null != startTime || null != endTime) {
            Criteria criteria = new Criteria();

            if (null != startTime) {
                criteria.andOperator(Criteria.where("recordTime").gte(startTime));
            }
            if (null != endTime) {
                criteria.andOperator(Criteria.where("recordTime").lte(endTime));
            }
            query.addCriteria(criteria);

            // 查询总数，当查询条件不为空时用countDocuments统计数量，并给dts加索引以优化查询速度
            totalCount = mongoTemplate.count(query, SystemLog.class);
        }
        // 查询总数，当查询条件为空时用estimatedDocumentCount统计数量以优化查询速度
        else {
            totalCount = mongoTemplate.getCollection("systemLog").estimatedDocumentCount();
        }

        //增加分页条件
        query.with(page);

        //按时间倒叙
        query.with(Sort.by(Sort.Direction.DESC, "recordTime"));
        List<SystemLog> systemLogs = mongoTemplate.find(query, SystemLog.class);

        return new PageImpl<>(systemLogs, page, totalCount);
    }
}
